const Writable = require('stream').Writable;
console.log(Writable);

const util=require('util');

module.exports=CountStream;

util.inherits(CountStream,Writable);

function CountStream(matchText,options){
    const _this = this;
    Writable.call(_this,options);
    _this.count=0;
    _this.matcher=new RegExp(matchText,'ig');
}

CountStream.prototype._write=function (chunk,encoding,cb){
    var matches=chunk.toString().match(this.matcher);
    if(matches){
        this.count+=matches.length;
    }
    cb();
}

CountStream.prototype.end=function (){
    this.emit('total',this.count);
};